package service;

import mapper.StandardsMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.Standards;
import util.SqlSessionFactoryUtil;

import java.util.List;

public class StandardsService {
    private final SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtil.getSqlSessionFactory();

    public List<Standards> selectAllStandards() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StandardsMapper standardsMapper = sqlSession.getMapper(StandardsMapper.class);

        List<Standards> standards = standardsMapper.selectAll();

        sqlSession.close();
        return standards;
    }

    public double selectPriceOfTicketType(Standards standard) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StandardsMapper mapper = sqlSession.getMapper(StandardsMapper.class);

        List<Standards> standards = mapper.selectOneOfTicketType(standard.get_ticketType());
        double price = standards.isEmpty() ? -1 : standards.get(0).get_price();

        sqlSession.close();
        return price;
    }

    public void updateAllTicketPrices(List<Standards> standards) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StandardsMapper mapper = sqlSession.getMapper(StandardsMapper.class);

        for (Standards standard : standards) {
            mapper.updateTicketPrice(standard);
        }

        sqlSession.commit();
        sqlSession.close();
    }
}
